﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Configuration.Install;
using System.Collections;

namespace uk.ac.soton.ses
{
    static class Program
    {
        private readonly static string[] _usageStrings = {string.Format("Usage: {0} <command>",System.Reflection.Assembly.GetExecutingAssembly().GetName().Name),
                                                              "Commands:",
                                                              "\t/?                   Help",
                                                              "\tinstall              Installs service",
                                                              "\tuninstall            Uninstalls service",
                                                              "\tmonitor              Monitor using directory specified in config file"
                                                          };
        private static void Usage()
        {
            foreach (string s in _usageStrings)
            {
                Console.WriteLine(s);
            }
        }

        private static bool InstallMetadataSyncService()
        {
            try
            {
                string binDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).Location);
                string serviceExe = Path.Combine(binDirectory, "HDCMetadataSyncService.exe");
                string serviceInstallLog = Path.ChangeExtension(serviceExe, ".InstallLog");

                // Create an object of the 'AssemblyInstaller' class.
                using (AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller())
                {
                    //Set the properties to install the required assembly.
                    myAssemblyInstaller.Path = serviceExe;
                    myAssemblyInstaller.Context = new InstallContext(serviceInstallLog, null);
                    myAssemblyInstaller.Context.Parameters["assemblypath"] = string.Format("\"{0}\" {1}", Path.Combine(binDirectory, "HDCMetadataSyncService.exe"), "/service");
                    // Clear the 'IDictionary' object.
                    IDictionary mySavedState = new Hashtable();
                    mySavedState.Clear();

                    //Install the assembly.
                    myAssemblyInstaller.Install(mySavedState);

                    //Commit the assembly.
                    myAssemblyInstaller.Commit(mySavedState);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("There was an error installing: {0}", ex.Message));
                return false;
            }
            return true;
        }

        private static bool UninstallMetadataSyncService()
        {
            try
            {
                string binDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).Location);

                Console.WriteLine(string.Format("Using TransactedInstaller"));
                using (TransactedInstaller transactedInstaller = new TransactedInstaller())
                {
                    //Create a new Install Context
                    transactedInstaller.Context = new InstallContext(@"HDCUninstall.log", null);

                    // Create an object of the 'AssemblyInstaller' class.
                    using (AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller())
                    {
                        //Set the path
                        myAssemblyInstaller.Path = Path.Combine(binDirectory, "HDCMetadataSyncService.exe");

                        //Add the AssemblyInstaller to the TransactedInstaller
                        transactedInstaller.Installers.Add(myAssemblyInstaller);

                        Console.WriteLine(string.Format("Uninstalling"));

                        // Uninstall the assembly.
                        transactedInstaller.Uninstall(null);
                        Console.WriteLine(string.Format("...done."));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("There was an error installing: {0}", ex.Message));
                return false;
            }
            return true;
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static int Main(string[] args)
        {
            bool success = false;
            if (args.Length == 0)
            {
                Console.WriteLine("Monitor via console application...");
                Console.WriteLine("Press ENTER to stop monitoring.");
                Trace.AutoFlush = true;
                Trace.Listeners.Add(new ConsoleTraceListener());
                Trace.WriteLine("----");
                HDCConfigurationOptions configOptions = HDCConfiguration.GetConfigurationOptions();
                string folderToWatch = configOptions.FileSystemWatcherOptions.LocalPath;
                Trace.WriteLine(string.Format("Starting watcher with folder {0}", folderToWatch));
                using (HDCFileSystemWatcher materials_fsw = new HDCFileSystemWatcher(configOptions.FileSystemWatcherOptions))
                {
                    Console.ReadLine();
                    Console.WriteLine("Enter pressed. Shutting down.");
                    Trace.Close();
                    return 0;
                }
            }

            for (int i = 0; i < args.Length; i++)
            {

                string thisArg = args[i];
                switch (thisArg.ToLower())
                {
                    case "/?":
                    case "/h":
                    case "/help":
                    case "-help":
                    case "--help":
                    case "help":
                        Program.Usage();
                        success = true;
                        break;

                    case "install":
                    case "-install":
                    case "/install":
                        Console.WriteLine("Installing...");
                        success = Program.InstallMetadataSyncService();
                        break;

                    case "uninstall":
                    case "-uninstall":
                    case "/uninstall":
                        Console.WriteLine("Uninstalling...");
                        success = Program.UninstallMetadataSyncService();
                        break;

                    case "service":
                    case "-service":
                    case "/service":
                        //Start the service
                        ServiceBase.Run(new HDCMetadataSyncService());
                        success = true;
                        break;

                    default:
                        Program.Usage();
                        success = false;
                        break;
                }

            }

            return success ? 0 : 1;
        }
    }
}
